<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TodoList</title>
    <style>
        .completed {
            text-decoration: line-through;

        }

        .selected {
            background-color: #42b983;
            color: red;
        }
        .empty{
            border-color: red;
        }
    </style>
</head>
<body>
<div id="tolove-app">
  <div>
      添加一个你的心愿吧（回车即可添加）！
      <input type="text" placeholder="添加心仪的Girl" v-model="newTodoTitle"
      @keyup.enter="addTodo" :class="{empty:inputEmpty}"><span v-if="inputEmpty" style="color: red;">输入你想和新茶做的事</span>
  </div>

    <div>
        <ul>
            <li v-for="todo in filterTodos" :key="todo.id" >
                <span :class="{completed :todo.completed}" @dblclick="todoEdit(todo)">{{todo.title}}</span>
              <input v-if="!todo.completed" type="button" value="标为完成" @click="todoComplete(todo)"  >
              <input v-if="todo.completed" type="button" value="标为未完成" @click="todoNotComplete(todo)"  >
                <input type="button" value="删除" @click="removeTodo(todo)">
                <input type="text" value="编辑 tolove..." v-if="editedTodo!=null && todo.id==editedTodo.id" v-model="todo.title"
                @keyup.enter="editDone(todo)" @keyup.esc="cancelEdit(todo)" v-focus="true">
            </li>
        </ul>
        <div v-if="todos.length">

            <span v-if="leftUnTodoCount">剩余{{leftUnTodoCount}}未完成</span>
            <span v-else-if="completedTodosCount">恭喜你完成了所有心愿！</span>

            <input type="button" @click="markAllComplete" value="标记所有已完成">
            <input type="button" @click="intent='completed'" :class="{selected:intent=='completed'}" value="已完成">
            <input type="button" @click="intent='ongoing'" :class="{selected:intent=='ongoing'}" value="办理中">
            <input type="button" @click="intent='all'" :class="{selected:intent=='all'}" value="全部事项">
            <input type="button" value="清除已完成" @click="clearCompleted">
            <input type="button" value="清除全部" @click="clearAll">

        </div>
        <input type="button" value="找回删除" @click="regret" v-if="hasRemoveTodos">
    </div>
</div>
<script src="../js/vue.js"></script>
<script>
    let id=0;

    var STORAGE_KEY = 'girltodos';
    var todoStorage = {
        fetch: function () {
            var todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            todos.forEach(function (todo, index) {
                todo.id = index
            });
            todoStorage.uid = todos.length;
            return todos
        },
        save: function (todos) {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
        }
    };
    var app=new Vue({
        el: '#tolove-app',
        data:function () {
            return {
                todos:todoStorage.fetch(),
                recycleBin:[],
                newTodoTitle:"",
                inputEmpty:false,
                editedTodo:null,
                intent:"all",
                hasRemoveTodos:false
            }
        },

        watch:{
            todos:{
              handler:function (todos) {
                  todoStorage.save(todos)
              }  ,
                deep:true
            }
        },
        directives:{
          focus:{
              inserted:function (el) {
                  el.focus()
              }
          }
        },
        methods:{
            addTodo:function () {
                if(this.count){
                    this.todos.push({id:todoStorage.uid++,title:this.newTodoTitle,completed:false})
                    this.inputEmpty=false
                }else {
                    this.inputEmpty=true
                }

                this.newTodoTitle=""
            },
            todoComplete:function (todo) {
                console.log(todo.id+" "+todo.title+" "+todo.completed)
                todo.completed=true

            },
            todoNotComplete:function (todo) {
                console.log(todo.id+" "+todo.title+" "+todo.completed)
                todo.completed=false

            },
            removeTodo:function (todo) {
                if(!confirm("确认删除吗？"))
                    return
                //this.todos.indexOf(todo) 用来定位元素的位置，然后我们删除掉这个位置的元素 splice(index, 1)，1 表示只删除一个，即当前位置（index 的值）的元素。
                this.recycleBin.push(todo)
                this.todos.splice(this.todos.indexOf(todo),1)
                this.hasRemoveTodos=true
            },
            regret: function () {

              /*  for (var i = 0; i < this.recycleBin.length; i++) {
                    var t=this.recycleBin[i]
                    var todo={id:t.id,title:t.title,completed:t.completed}
                    this.todos.push(todo)
                }
                */
               this.todos=this.todos.concat(this.recycleBin.slice())
                this.recycleBin=[]
                this.hasRemoveTodos=false
            },
            todoEdit:function (todo) {
                this.editedTodo={id:todo.id, title:todo.title,completed:todo.completed}
                console.log("editedTodo:"+this.editedTodo.title)

            },
            editDone:function (todo) {
                if(todo.title.trim().length==0){
                    this.removeTodo(todo);
                    return;
                }
                 this.editedTodo=null

            },
            cancelEdit:function (todo) {
                todo.title=this.editedTodo.title
                this.editedTodo=null
            },
            markAllComplete:function () {
              /*  for(var i=0;i<this.todos.length;i++){
                    todo=this.todos[i]
                    console.log("markAllComplete "+todo.id+" "+todo.title+" "+todo.completed)
                    if (todo.completed == false) {
                        this.todoComplete(todo)
                    }
                }*/
              this.todos.map(function (todo) {
                  if (todo.completed == false) {
                      todo.completed=true
                  }
              })
            },
            clearCompleted:function () {
               var todoCompleteds=this.todos.filter(todo=>todo.completed).slice() //过滤出数组，然后复制一个

              /*  for (var i = 0; i < todoCompleteds.length; i++) {
                    var t=todoCompleteds[i]
                    var todo={id:t.id,title:t.title,completed:t.completed}
                    this.recycleBin.push(todo)
                }*/
              //this.recycleBin.map(this.recycleBin.push,todoCompleteds)

                this.recycleBin=this.recycleBin.concat(todoCompleteds)
                console.log("clearCompleted "+this.recycleBin)
               this.todos= this.todos.filter(todo=>!todo.completed)
                this.hasRemoveTodos=true


            },
            clearAll:function () {
                if(!confirm("你确认要删除全部数据吗？")){
                    return;
                }
               /* for (var i = 0; i < this.todos.length; i++) {
                    var t=this.todos[i]
                    var todo={id:t.id,title:t.title,completed:t.completed}
                    this.recycleBin.push(todo)
                }*/
                this.recycleBin=this.recycleBin.concat(this.todos.slice())
                this.todos=[]
                this.hasRemoveTodos=true
            }

        },
        computed:{
            count:function () {
                return this.newTodoTitle.length;
            },
         leftUnTodoCount:function () {
                var n=0;
                this.todos.map(function (todo) {
                    if (todo.completed == false) {
                        n=n+1;
                        console.log("leftUnTodoCount "+n)
                    }
                })
               console.log("leftUnTodoCount total "+n)
                return n;
            },
            completedTodos: function () {
                return this.todos.filter(todo => todo.completed)
            },
            completedTodosCount: function () {
                return this.completedTodos.length
            },
           /* leftUnTodoCount: function () {
                var n =this.todos.filter(todo => !todo.completed).length;
                console.log("leftUnTodoCount total "+n)
                 return n;
             }*/
           filterTodos:function () {
               if (this.intent == "completed") {
                   return this.todos.filter(todo=>todo.completed)
               }else if(this.intent == "ongoing"){
                   return this.todos.filter(todo=>!todo.completed)
               }else{
                   return this.todos
               }
           }
        }
    })
</script>
</body>
</html>
